import { openWin } from '@/utils/helpers';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import avatar from '@/static/avatar.png'
import type { TeamNumTypes } from '@/common/types/TeamNumTypes';

export interface userTypes {
    id: number | string | null
    avatar: string
    order_sum: number |string| null
    team_sum: number |string| null
    team_num: TeamNumTypes|number|string | null
    amount: string | number
    amount_total: string | number
    wechat_openid: string
    username: string
    nickname: string
    password?: string
    token?: string
    match_total:number|string
    vip_expire_time?: string | null
    is_vip?: boolean | null
    is_dealer?: boolean | null
    withdrawal_url?:string
}
export const userInfoInit = {
    id: '',
    avatar: avatar,
    amount: "0",
    order_sum: null,
    team_sum: 0,
    team_num: 0,
    amount_total: "0",
    wechat_openid: "",
    username: "",
    nickname: "请先登录",
    match_total:0,
    vip_expire_time: null,
    is_vip: false,
    is_dealer: false,
    withdrawal_url:'',
}

export const useUserStore = defineStore('user', () => {
    // 用户信息
    const userInfo = ref<userTypes>({ ...userInfoInit })

    // 设置用户信息
    const setUserInfo = (data: userTypes) => {
        if (data?.token) {
            const token = data.token
            uni.setStorageSync('token', token);
        }
        userInfo.value = data;
    }
    // 获取用户信息
    const getUserInfo = () => {
        const token = uni.getStorageSync("token");
        let user: userTypes = { ...userInfoInit };
        if (token) {
            uni.$u.http.get("Users/index").then((res: any) => {
                user = res?.data ? res?.data : user;
                setUserInfo(user);
            });
        }
    }
    // 用户退出
    const loginOut = async () => {
        uni.showModal({
            title: "温馨提示",
            content: "是否确认退出登录吗？",
            success: (res) => {
                if (res.confirm) {
                    uni.removeStorageSync("token");
                    setUserInfo(userInfoInit)
                    openWin({ url: '/pages/index/index' }, 'reLaunch');
                }
            },
        });
    }
    return {
        userInfo,
        setUserInfo,
        getUserInfo,
        loginOut
    }
});